import java.io.*;
        import java.math.BigInteger;
        import java.security.KeyPair;
        import java.security.KeyPairGenerator;
        import java.security.PrivateKey;
        import java.security.PublicKey;
        import java.security.interfaces.RSAPublicKey;

public class RSA_Use {
    //生成公钥、私钥。
    public static void produceRSAKey() throws Exception {
        KeyPairGenerator kpg=KeyPairGenerator.getInstance("RSA");//创建密钥生成器
        kpg.initialize(1024);//初始化密钥生成器
        KeyPair kp=kpg.genKeyPair();//生成密钥对
        PublicKey pbkey=kp.getPublic();//获取公钥
        PrivateKey prkey=kp.getPrivate();//获取私钥
        //  保存公钥
        FileOutputStream f1=new FileOutputStream("Skey_RSA_pub.dat");
        ObjectOutputStream b1=new  ObjectOutputStream(f1);
        b1.writeObject(pbkey);
        //  保存私钥
        FileOutputStream  f2=new FileOutputStream("Skey_RSA_priv.dat");
        ObjectOutputStream b2=new  ObjectOutputStream(f2);
        b2.writeObject(prkey);
    }
    //RSA加密。
    public static void EncryptionRSA(byte[]data) throws Exception {
        FileInputStream f=new FileInputStream("Skey_RSA_pub.dat");
        ObjectInputStream b=new ObjectInputStream(f);
        RSAPublicKey pbk=(RSAPublicKey)b.readObject( );
        BigInteger e=pbk.getPublicExponent();//获取公钥的参数e,n。
        BigInteger n=pbk.getModulus();
        System.out.println("e= "+e);
        System.out.println("n= "+n);
        // 明文 m
        BigInteger m=new BigInteger(data);
        // 计算密文c,打印
        BigInteger c=m.modPow(e,n);
        System.out.println("c= "+c);
        // 保存密文
        String cs=c.toString( );//以字符串的形式保存
        BufferedWriter out=
                new BufferedWriter(new OutputStreamWriter(
                        new FileOutputStream("Enc_RSA.dat")));
        out.write(cs,0,cs.length( ));
        out.close( );
    }
}

